/**
 * \file ThreadManager_Win32.cpp
 * \brief ThreadManager declaration class
 * \author Edouard ROGE
 * \date 29 august 2012
 */

#include <Windows.h>
#include <process.h> 

#include "Thread.h"
#include "ThreadManager.h"

namespace Core
{
	namespace Thread
	{
		ThreadManager::ThreadManager()
		{
			m_Threads.reserve(MAX_THREAD);
		}

		ThreadManager::~ThreadManager()
		{

		}

		uint32 ThreadManager::GetMaxThread() const
		{
			return MAX_THREAD;
		}

		uint32 ThreadManager::GetRunningThreads() const
		{
			return m_Threads.size();
		}

		void ThreadManager::Register(Thread * _pThread)
		{
			_pThread->m_parentThread = GetCurrentThreadId();
			m_Threads.push_back(_pThread);
			_pThread->m_handle = CreateThread(NULL, 0, Thread::RunThread, _pThread, 0, NULL);
		}

		void ThreadManager::Unregister(Thread * _pThread)
		{
			std::vector<Thread*>::const_iterator it = std::find(std::begin(m_Threads), std::end(m_Threads), _pThread);
			if (it != m_Threads.end())
			{
				CloseHandle(_pThread->m_handle);
				m_Threads.erase(it);
			}
		}

		void ThreadManager::Clear()
		{
			for (uint32 i = 0; i < m_Threads.size(); ++i)
				WaitForSingleObject(m_Threads[i]->m_handle, INFINITE);

			m_Threads.clear();
		}
	}
}